package h5

import (
	"chess_platform/controllers"
	. "chess_platform/internal/common"
	"chess_platform/internal/token"
	"encoding/json"
	"fmt"
	"time"
)

type BaseUserInfo struct {
	Uid    int64 `json:"uid"`
	Level  int64 `json:"level"`
	Status int64 `json:"Status"`
}

type BaseController struct {
	controllers.BaseController
	BaseUserInfo
}

type GrantController struct {
	BaseController
}

func (b *BaseController) Prepare() {
	b.Res = new(controllers.Response)
	LogH5.Debug("用户输入:" + string(b.Ctx.Input.RequestBody))
	LogH5.Debug(fmt.Sprintf("用户访问(ID:%v)url:%v", b.Uid, b.Ctx.Input.URL()))
}

func (b *BaseController) Finish() {
	//访问成功之后更新缓存里token的时间
	if b.Uid != 0 {
		key := fmt.Sprintf("%v%v", KeyH5TokenCache, b.Uid)
		RedisCache.Expire(key, time.Duration(Secret.H5TokenCacheExpire)*time.Second)
	}
	data, _ := json.Marshal(b.Data["json"])
	LogH5.Debug(fmt.Sprintf("用户(ID:%v)访问url:%v返回值:%v", b.Uid, b.Ctx.Input.URL(), string(data)))
}

func (b *GrantController) Prepare() {
	LogH5.Debug("用户输入:" + string(b.Ctx.Input.RequestBody))
	LogH5.Debug("用户访问url:" + b.Ctx.Input.URL())

	b.Res = new(controllers.Response)
	var t controllers.Token
	err := b.Unmarshal(&t)
	if err != nil {
		b.Res.Code = Fail
		b.Res.Msg = "没带token访问:" + err.Error()
		b.Response()
		return
	}
	ex, err := token.Parse(t.Token)
	if err != nil || ex.GetTokenType() != TokenH5 {
		LogH5.Error(fmt.Sprintf("token解析错误:%v,或不是此H5类型的token", err))
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserUnauthorized
		b.Response()
		return
	}
	b.Uid = ex.GetId()

	keyAccessLimit := fmt.Sprintf("H5UserLimit-%v", b.Uid)
	if !AccessLimit(keyAccessLimit, Al.Frequency, Al.ExpireTime) {
		b.ResponseFail("操作过于频繁，请稍候再操作")
		return
	}

	b.Level = ex.GetLevel()
	status, _ := ex.GetInfo().(float64)
	b.Status = int64(status)
	if b.Status != FirstTopUpSuccess {
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgUserNotPass
		b.Response()
		return
	}
	LogH5.Debug(fmt.Sprintf("用户访问(ID:%v,Level:%v,Status:%v)url:%v", b.Uid, b.Level, b.Status, b.Ctx.Input.URL()))

	//cache里不存在说明token已经过期了
	key := fmt.Sprintf("%v%v", KeyH5TokenCache, b.Uid)
	if ex.IsExpire() || !RedisCache.IsExist(key) {
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserExpire
		b.Response()
		return
	}

	//cache里的token与传进来的不一样的话表示此帐号在其它地方登录了
	tokenCache := RedisCache.GetString(key)
	if tokenCache != "" { // token存在缓存里
		if string(tokenCache) != t.Token {
			b.Res.Code = ErrAlreadyLogin
			b.Res.Msg = MsgErrAlreadyLogin
			b.Response()

			return
		}
	} else { //token不存在缓存里
		b.Res.Code = ErrUserUnauthorized
		b.Res.Msg = MsgErrUserUnauthorized
		b.Response()
		return
	}

}

func (b *GrantController) IsLevel1() bool {
	if b.Level != Level1 {
		b.Res.Code = ErrUserForbidden
		b.Res.Msg = MsgErrUserForbidden
		b.Response()
		return false
	}
	return true
}
